import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STComponent, STColumn, STChange, STRequestOptions, STData } from '@delon/abc/st';
import { SFComponent, SFSchema, SFDateWidgetSchema } from '@delon/form';
import { NzModalService } from 'ng-zorro-antd/modal';
import { FreightAccountService } from 'src/app/routes/financial-management/services/freight-account.service';
import Big from 'src/app/shared/utils/deal-precision';
import { AccountManagemantService } from '../../services/account-managemant.service';


@Component({
  selector: 'app-partner-account-management-withdrawals-record',
  templateUrl: './withdrawals-record.component.html',
  styleUrls: ['../../../../commom/less/box.less', '../../../../commom/less/expend-but.less']
})
export class PartnerAccountManagementWithdrawalsRecordComponent implements OnInit {
  @ViewChild('st', { static: true }) st!: STComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  @ViewChild('auditModal', { static: false }) auditModal!: any;
  @ViewChild('viewReasonModal', { static: false }) viewReasonModal!: any;
  columns: STColumn[] = this.initST();
  searchSchema: SFSchema = this.initSF();

  _$expand = false;

  selectedRows: any[] = [];
  totalCallNo = 0;
  refundStatus: any = '';

  msg = '';
  constructor(public service: FreightAccountService, public amService: AccountManagemantService, private nzModalService: NzModalService, private router: Router, public ar: ActivatedRoute) { }

  ngOnInit(): void { }

  beforeReq = (requestOptions: STRequestOptions) => {
    if (this.sf) {
      Object.assign(requestOptions.body, {
        ...this.sf?.value,
        createTime: {
          start: this.sf?.value.createTime?.[0] || '',
          end: this.sf?.value.createTime?.[1] || ''
        },
        refundStatus: this.refundStatus || null
      });
    }
    return requestOptions;
  };

  afterRes = (data: any[], rawData?: any) => {
    data = data.map(node => ({ ...node, 
      disabled: node.refundStatus !== '1'
     }));
    return data;
  };

  stChange(e: STChange): void {
    if (e.type === 'checkbox') {
      const checkRows = (e.checkbox as STData[]) || [];
      //判断当前页是否有选中的行
      if (checkRows.length === 0) {
        // 当前页没有存在已勾选的行，移除之前所记录的当前页的行
        const stList = this.st.list;
        stList.forEach(item => {
          this.selectedRows = this.selectedRows.filter((e: any) => e.id !== item.id);
        })
      } else {
        //添加新增的行
        checkRows.forEach((item: any) => {
          const newSelectedList = this.selectedRows.filter((r: any) => r.id === item.id);
          if (newSelectedList.length === 0) {
            this.selectedRows.push(item);

          }
        })
        // 移除取消选中的行
        const stList = this.st.list;
        stList.forEach(item => {
          if (!item.checked) {
            
            const index = this.selectedRows.findIndex(_item => item.id === _item.id);
            if (index !== -1) this.selectedRows.splice(index, 1);
          }
        })
      }
      let totalCallNo = 0;
      this.totalCallNo = 0;
      this.selectedRows.forEach((item => {
        totalCallNo = new Big(this.totalCallNo).plus(item?.amount).parse();
      this.totalCallNo = totalCallNo;
      }));
      
    } else if (e.type === 'loaded') {
      // 页面加载时勾选
      (e?.loaded || []).forEach((r) => {
        this.selectedRows.forEach((x) => {
          if (x.id === r.id) {
            r.checked = true;
          }
        });
      });
    }
  }

  changeRefundStatus(status?: string) {
    this.refundStatus = status || null;
    this.st.load(1);
  }

  auditAction(item?: any) {
    this.msg = '';
    let params: Array<string> = [];
    if (item) {
      params = [item.id];
    } else {
        
      if (this.selectedRows.length <= 0) {
        this.service.msgSrv.error('请选择提现单！');
        return;
      }
      params = this.selectedRows.map(node => node.id);
    }
    const modal = this.nzModalService.create({
      nzTitle: '审核',
      nzContent: this.auditModal,
      nzFooter: [
        {
          label: '拒绝',
          type: 'default',
          onClick: () => {
            if (!this.msg || this.msg.trim().length === 0) {
              this.service.msgSrv.warning('请填写拒绝原因 ');
              return false;
            }
            this.service
              .request(this.service.$api_disagree_refund, {
                refundApplicationId: params,
                msg: this.msg
              })
              .subscribe(res => {
                if (res) {
                  this.service.msgSrv.success('审核拒绝成功');
                  modal.destroy();
                  this.st.load(1);
                }
              });
            return false;

          }
        },
        {
          label: '通过',
          type: 'primary',
          onClick: () => {
            this.service
              .request(this.service.$api_agree_refund, {
                refundApplicationId: params,
                msg: this.msg
              })
              .subscribe(res => {
                if (res) {
                  this.service.msgSrv.success('审核通过成功');
                  modal.destroy();
                  this.st.load(1);
                }
              });
          }
        }
      ]
    });
    modal.afterClose.subscribe(res => {
      this.st.load();
    });
  }

  showReason(item: any) {
    const modal = this.nzModalService.create({
      nzTitle: '查看原因',
      nzContent: item?.rejectionCause || item?.failCause,
      nzFooter: [
        {
          label: '关闭',
          type: 'primary',
          onClick: () => {
            modal.destroy();
          }
        }
      ]
    });
  }

  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
    this._$expand = false;
  }

  /**
   * 伸缩查询条件
   */
  expandToggle() {
    this._$expand = !this._$expand;
    this.sf?.setValue('/expand', this._$expand);
  }

  private initSF(): SFSchema {
    return {
      properties: {
        expand: {
          type: 'boolean',
          ui: {
            hidden: true
          }
        },
        refundApplyCode: {
          type: 'string',
          title: '提现单号',
          ui: {
            placeholder: '请输入'
          }
        },
        refundStatus: {
          type: 'string',
          title: '提现状态',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'refund:apply:status' },
            placeholder: '请选择'
          }
        },
        createTime: {
          title: '提现时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd',
            placeholder: '请选择',
            nzShowTime: true
          } as SFDateWidgetSchema
        },
        bankAccountName: {
          type: 'string',
          title: '账户名称',
          ui: {
            placeholder: '请输入',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        accountType: {
          type: 'string',
          title: '账户类型',
            ui: {
              widget: 'dict-select',
              params: { dictKey: 'bank:type' },
              placeholder: '请选择',
              visibleIf: {
                expand: (value: boolean) => value
              }
            }
        },
        ltdId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.service.getNetworkFreightForwarder(),
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        bankType: {
          type: 'string',
          title: '银行类型',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'bankname:type' },
            placeholder: '请输入',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        }
      }
    };
  }

  private initST(): STColumn[] {
    return [
      { title: '', index: 'key', type: 'checkbox', className: 'text-center' },
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return (this.st.pi * this.st.ps) - this.st.ps + idx + 1 + ''
        }
      },
      { title: '提现时间', index: 'createTime', width: 180, className: 'text-center' },
      { title: '提现单号', index: 'refundApplyCode', width: 180, className: 'text-center' },
      { title: '网络货运人', index: 'ltdName', width: 220, className: 'text-center' },
      { title: '银行类型', index: 'bankTypeLabel', width: 100, className: 'text-center' },
      { title: '账户类型', index: 'accountTypeLabel', width: 100, className: 'text-center' },
      { title: '账户名称', index: 'bankAccountName', width: 220, className: 'text-center' },
      { title: '虚拟账户', index: 'virtualAccount', width: 180, className: 'text-center' },
      {
        title: '提现金额',
        index: 'amount',
        width: 200,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.amount }) }
      },
      { title: '提现银行账户', render: 'bankCardNumber', width: 200, className: 'text-center' },
      { title: '提现状态', index: 'refundStatusLabel', width: 100, className: 'text-center' },
      { title: '银行流水号', index: 'bankSerialNumber', width: 160, className: 'text-center' },
      { title: '核心交易流水', index: 'coreSerNo', width: 180, className: 'text-center' },
      { title: '失败原因', index: 'rejectionCause', width: 200, format: item => item.failCause, className: 'text-center' },
      {
        title: '操作',
        fixed: 'right',
        width: '110px',
        buttons: [
          {
            text: '查看回单',
            iif: item => item.refundStatus === '3',
            acl: { ability: ['AM-WITHDRAW-RECORD-viewRefund'] },
            click: item =>
              this.service.getReceiptUrl(item.receiptUrl, {
                bankType: item.bankType,
                rmYll: item.userId,
                snglFlgCd: item.coreSerNo,
                bussType: '06',
                ltdId: item.ltdId,
                accountType: item.accountType
              })
          },
          {
            text: '查看原因',
            iif: item => item.refundStatus === '4',
            acl: { ability: ['AM-WITHDRAW-RECORD-viewResult'] },
            click: item => this.showReason(item)
          },
          {
            text: '审核',
            iif: item => item.refundStatus === '1',
            acl: { ability: ['AM-WITHDRAW-RECORD-oneAudit'] },
            click: item => this.auditAction(item)
          },
          {
            text: '详情',
            acl: { ability: ['AM-WITHDRAW-RECORD-detail'] },
            click: item => this.router.navigate(['./../detail/' + item.id], { relativeTo: this.ar })
          }
        ]
      }
    ];
  }
}
